<template>
  <div class="patient-reported-left">
    <div class="top">
      <div class="subject-info">
        <div v-for="(row, i) in localSubjectInfo" :key="i">
          <span>{{ row.variableName }}：</span>
          <span>{{ row.variableValueName ? row.variableValueName : row.variableValue }}</span>
        </div>
      </div>
    </div>
    <div class="down">
      <div class="visits">
        <div class="icons">
          <i
            class="left el-icon-monitor colorHover"
            @click="
              setMode(0)
              setTable(null)
              setPriority([])
              setInStyle()
            "
          ></i>
          <i class="right el-icon-circle-plus-outline colorHover">
            <el-dropdown size="medium" trigger="click" @command="handleCommand">
              <span class="el-dropdown-link">&nbsp;</span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="addVisit">增加访视</el-dropdown-item>
                <el-dropdown-item command="auditTrail">稽查轨迹</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </i>
        </div>
        <div class="choose">
          <el-select
            size="mini"
            v-model="selected"
            filterable
            placeholder="请选择"
            :clearable="true"
            value-key="id"
            :loading="loadingVisitList"
          >
            <el-option v-for="visit in visitList" :key="visit.id" :label="visit.visitName" :value="visit">
              <div class="option-row-box">
                <span>{{ visit.visitName }}</span>
                <div v-if="visit.visitType == 3">
                  <i class="el-icon-folder-add" @click.stop="handleOptionClick('add', visit)"></i>
                  <i class="el-icon-delete" @click.stop="handleOptionClick('del', visit)"></i>
                </div>
              </div>
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="blank"></div>
      <div class="form-navigation">
        <ul>
          <li
            v-for="(table, index) in tableList"
            :key="index"
            :id="`t-${table.visitTableId}`"
            @click="handlePriority(table)"
          >
          <span
              :class="
                `data-${findState(table.extandStatus)} frozen-${table.extandStatus.frozenState}`
              "
            ></span>
            <i class="el-icon-edit" v-if="table.extandStatus.piState === 1"></i>
            <i :class="`sign sign-${table.extandStatus.piState}`" v-else></i>
            <span class="audit-box">
              <span
                v-for="(audit, index) in audits"
                :title="audit.checkName"
                :class="`audit audit-${findAuditState(audit, table)}`"
                :key="index"
              ></span>
            </span>
            <span
              :class="
                `question question-${
                  table.extandStatus.questionState == 2
                    ? permissionController('subject::info::handle::challenge')
                      ? '2-2'
                      : '2-1'
                    : table.extandStatus.questionState
                }`
              "
            ></span>
            <span class="text">
              <template>
                <el-tooltip
                  v-if="table.tableName.length > 10"
                  effect="light"
                  :content="table.tableName"
                  placement="right-start"
                >
                  <span>{{ `${table.tableName.substring(0, 10)}...` }}</span>
                </el-tooltip>
                <span v-else>{{ table.tableName }}</span>
              </template>
            </span>
          </li>
        </ul>
      </div>
      <div class="blank"></div>
    </div>
    <el-dialog
      custom-class="dialog-edit-visit-table"
      :title="dialogVisitTitle"
      width="620px"
      :visible.sync="dialogVisitTableVisible"
    >
      <edit-visit-table
        v-if="dialogVisitTableVisible"
        :current-visit="currentVisit"
        @close="dialogVisitTableVisible = false"
      />
    </el-dialog>
    <el-dialog custom-class="dialog-add-visit" title="增加访视" width="620px" :visible.sync="dialogAddVisitVisible">
      <add-visit
        v-if="dialogAddVisitVisible"
        @close="dialogAddVisitVisible = false"
        @addVisitSuccess="handleCallback"
      />
    </el-dialog>
    <el-dialog
      custom-class="dialog-audit-trail"
      title="稽查轨迹"
      width="80%"
      :visible.sync="dialogAuditTrailVisible"
    >
      <audit-trail v-if="dialogAuditTrailVisible" :dialogAuditTrailVisible="dialogAuditTrailVisible" :subjectTables="subjectTables" :subjectVisit="subjectVisit" @close="dialogAuditTrailVisible = false" />
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
import EditVisitTable from './components/editVisitTable.vue'
import AddVisit from './components/addVisit.vue'
import AuditTrail from './components/auditTrail.vue'          
import { permissionController } from '@/utils/index'

export default {
  data() {
    return {
      visitList: [],
      loadingVisitList: false,
      dialogVisitTableVisible: false,
      dialogVisitTitle: '',
      currentVisit: null,
      selected: null,
      tableList: [],
      localSubjectInfo: [],
      dialogAddVisitVisible: false,
      dialogAuditTrailVisible: false,
      currentState: ['草稿', '审核中', '冻结'],
      updateBatchDataStatusVisible: false,
      currentTable: null,
      query: null,
      isFirst: true,
      subjectTables: [],
      subjectVisit: []
    }
  },
  components: { AddVisit, AuditTrail, EditVisitTable },
  created() {
    this.query = this.$route.query
    this.isFirst = true
    this.setTable(null)
    this.setVisit(null)
    
  },
  computed: {
    ...mapState({
      subjectInfo: state => state.treatment.subjectInfo,
      audits: state => state.treatment.audits,
      visit: state => state.treatment.visit,
      table: state => state.treatment.table,
      version: state => state.treatment.version,
    }),
    ...mapGetters({
      findRole: 'treatment/findRole',
    }),
    title: function () {
      if (this.currentTable) {
        if ([5, 6].includes(this.currentTable.extandStatus.tableStatus)) {
          return '提示'
        }
      }
    },
  },
  watch: {
    selected: {
      handler: function (val) {
        this.setVisit(val)
      },
    },
    visit: {
      handler: function (val) {
        this.setTable(null)
        this.setPriority([])
        this.selected = val
        val && this.findSubjectVisitTables()
      },
      deep: true,
      immediate: true,
    },
    table: {
      handler: function (val) {
        val && this.handleActiveStatus(val)
      },
      deep: true,
      immediate: true,
    },
    subjectInfo: {
      handler: function (val) {
        const { subjectDetails } = val
        subjectDetails &&
          subjectDetails.forEach(item => {
            const obj = {
              variableName: item.variableName,
              variableValue: item.variableValue,
              variableValueName: item.variableValueName,
            }
            this.localSubjectInfo.push(obj)
          })
        this.findSubjectVisits()
      },
      deep: true,
    },
    version: {
      handler: function () {
        this.findSubjectVisits(this.findSubjectVisitTables)
      },
    },
  },
  methods: {
    permissionController,
    ...mapActions('eCRFDetail', ['subjectVisits', 'subjectVisitTables', 'subjectVisitAddSelect', 'removeSubjectVisit', 'getSelectTerm']),
    ...mapMutations({
      setVisit: 'treatment/setVisit',
      setMode: 'treatment/setMode',
      setTable: 'treatment/setTable',
      setPriority: 'treatment/setPriority',
    }),
    // 选择访视
    handlePriority(current) {
      this.setTable(current)
      this.isFirst = false
      // 选中后按钮加上active
      this.handleActiveStatus(current)
      const priority = this.tableList.filter(table => {
        const {
          config: { priority },
          extandStatus: { tableStatus },
        } = table
        return priority > 0 && tableStatus === 0
      })
      const target = priority.filter(item => item.visitTableId == current.visitTableId)
      if (target && target.length > 0) {
        this.setPriority([])
      } else {
        this.setPriority(priority)
      }
    },

    findAuditState(audit, table) {
      const { roleCode } = audit
      const { extandStatus } = table
      const target = Object.keys(extandStatus).filter(key => {
        return key.indexOf(roleCode.toLowerCase()) >= 0
      })[0]
      return extandStatus[target]
    },

    findState (extandStatus) {
      if (extandStatus.isLapse === 2 || extandStatus.isLapse === 3) {
        return extandStatus.isLapse + 1
      }
      if (!extandStatus.isLapse||extandStatus.isLapse === 1 ) {
        return extandStatus.tableStatus
      }
    },

    handleCallback() {
      this.dialogAddVisitVisible = false
      this.findSubjectVisits()
    },

    handleCommand(command) {
      if (command === 'addVisit') {
        this.dialogAddVisitVisible = true
      } else {
        this.dialogAuditTrailVisible = true
        this.getOperateType()
      }
    },

    getOperateType () {
      const { id } = this.subjectInfo
      const params = {
        subjectId: id
      }
      this.getSelectTerm({ params }).then(res => {
        const { code, data } = res
        if (code === 200) {
          this.subjectVisit = data.subjectVisits || []
          this.subjectTables = data.subjectTables||[]
        }
      })
    },

    //点击访视增加样式
    handleActiveStatus(val) {
      setTimeout(() => {
        this.setMode(val && val.config && val.config.relationType)
        const lis = document.querySelectorAll('.patient-reported-left .form-navigation li')
        lis.forEach(li => {
          li && li.classList.remove('active')
        })
        const target = document.querySelector(`#t-${val && val.visitTableId}`)
        target && target.classList.add('active')
      })
    },
    // 获取访视列表数据
    findSubjectVisitTables() {
      const { id, databaseVersion } = this.subjectInfo
      const params = {
        subjectId: id,
        databaseVersion: databaseVersion,
        subjectVisitId: this.visit.id,
        // roleId: this.findRole.roleId
      }
      this.subjectVisitTables({ params })
        .then(res => {
          const { code, data, message } = res
          if (code === 200) {
            this.tableList = data
            if (!this.table) {
              if (data && data.length > 0) {
                let table
                if (Reflect.has(this.query, 'subjectTableId')) {
                  table = data.filter(item => item.id == this.query.subjectTableId)[0]
                  this.setTable(table)
                  this.handlePriority(table)
                
                } else {
                  table = data[0]
                }
                if (!this.isFirst) {
                  this.setTable(table)
                  this.handlePriority(table)
                }
              }
            } else {
              const target = this.tableList.filter(table => table.visitTableId == this.table.visitTableId)[0]
              this.setTable(target)
              if (!this.isFirst) {
                this.handlePriority(target)
              }
            }
            //  this.handleActiveStatus();
            const lis = document.querySelectorAll('.patient-reported-left .form-navigation li')
            lis.forEach(li => {
              li && li.classList.remove('active')
            })
          }
        })
        .catch(error => {
          this.tableList.length = 0
          this.$message.error(error)
        })
        .finally(() => {})
    },
    setInStyle() {
      const lis = document.querySelectorAll('.patient-reported-left .form-navigation li')
      lis.forEach(li => {
        li && li.classList.remove('active')
      })
    },
    removeSubjectVisits(visit) {
      const params = {
        subjectVisitId: visit.id,
        roleId: localStorage.getItem('roleId'),
      }

      this.removeSubjectVisit({ params })
        .then(res => {
          const { code, message } = res
          if (code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!',
            })
            this.findSubjectVisits()
          } else {
            this.$message.error(message)
          }
        })
        .catch(error => {
          this.$message.error(error)
        })
    },
    // 删除
    handleOptionClick(type, visit) {
      if (type == 'add') {
        this.dialogVisitTitle = visit.visitName
        this.dialogVisitTableVisible = true
        this.currentVisit = visit
      } else {
        this.$confirm('确定删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          this.removeSubjectVisits(visit)
        })
      }
    },
    // 获取访视表
    findSubjectVisits(fn) {
      this.loadingVisitList = true
      const { id, databaseVersion } = this.subjectInfo
      const params = {
        subjectId: id,
        databaseVersion,
      }
      if (this.subjectInfo.id) {
        this.subjectVisits({ params })
          .then(res => {
            const { code, data, message } = res
            if (code === 200) {
              this.visitList = data
              if (!this.visit) {
                if (data && data.length > 0) {
                  let visit
                  if (Reflect.has(this.query, 'visitId')) {
                    visit = data.filter(item => item.id == this.query.visitId)[0]
                  } else {
                    visit = data[0]
                  }
                  this.setVisit(visit)
                }
              }
              fn && fn()
            }
          })
          .catch(error => {
            this.$message.error(error)
          })
          .finally(() => {
            this.loadingVisitList = false
          })
      }
    },
  },
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
